package org.jrfe.gfx.g2d.text;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Scanner;

import org.jrfe.gfx.JRFERenderer;
import org.jrfe.res.Texture;
import org.jrfe.res.impl.TextureManagerImpl;
import org.jrfe.util.FileUtil;
import org.lwjgl.opengl.GL11;

public class Font {

	public class CharData{
		public int listId;
		public int height;
		public int width;
		public float xExtend;
		public float yExtend;
	}
	
	public static final String DELIMITER = ",";
	
	CharData [] charArray = new CharData[256];
	
	Texture texture;
	
	private DynamicText tmptext;
	
	public Font(String path,Texture fontTexture) throws IOException {
	 	this.texture = fontTexture;
		
	 	URL url = TextureManagerImpl.class.getClassLoader().getResource(path);
        
        if (url == null) {
            throw new IOException("Cannot find: " + path);
        }
	 	
	 	// Read data File
	 	List<String> dataFile = FileUtil.readFile(path);
	 	
	 	// Genearate Lists
	 	int list = GL11.glGenLists(256);
	 	for(int i = 0; i < charArray.length;i++){
	 		CharData cd = new CharData();
	 		cd.listId = list;
	 		charArray[i] = cd;
	 		list++;
	 	}
	 	
	 	Scanner scanner;
	 	
	 	float aw  = fontTexture.getSRatio();
	 	float ah  = fontTexture.getTRatio();
	 	
	 	for(String dataLine : dataFile){
	 		if(dataLine.startsWith("#")){
	 			continue;
	 		}
	 		
	 		char c = dataLine.charAt(6);
	 		scanner = new Scanner(dataLine.substring(9));
	 		scanner.useDelimiter(DELIMITER);
	 	
	 			 		
	 		int tx = scanner.nextInt();
	 		int ty = scanner.nextInt();
	 		int tw = scanner.nextInt();
	 		int th = scanner.nextInt();
	 		int tx2 = tx + tw;
	 		int ty2 = ty + th;
	 		
	 		float xext = tw / 2.f;
	 		float yext = th / 2.f;
	 		
	 		CharData cd = charArray[c];
	 		cd.width = tw;
	 		cd.height = th;
	 		cd.xExtend = xext;
	 		cd.yExtend = yext;
	 		
	 		GL11.glNewList(cd.listId, GL11.GL_COMPILE);
	 		GL11.glBegin(GL11.GL_QUADS);
	 			GL11.glTexCoord2f(tx2 * aw, ty * ah); GL11.glVertex3f(xext, yext, 0);	
	 			GL11.glTexCoord2f(tx * aw, ty * ah); GL11.glVertex3f(-xext, yext, 0);
	 			GL11.glTexCoord2f(tx * aw, ty2 * ah); GL11.glVertex3f(-xext, -yext, 0);
	 			GL11.glTexCoord2f(tx2 * aw, ty2 * ah); GL11.glVertex3f(xext, -yext, 0);
	 		GL11.glEnd();
	 		GL11.glEndList();
	 	}
	 	
	 	tmptext = createDynamicText();
	 	
	}
	
	public DynamicText createDynamicText(){
		return new DynamicText(this);
	}
	
	public StaticText createStaticText(String text){
		return new StaticText(text,this);
	}
	
	public void renderString(String s,float x,float y){
		
		tmptext.setText(s);
		tmptext.getLoc().set(x, y);
		JRFERenderer.renderText(tmptext);
	}
	
	public Texture getTexture() {
		return texture;
	}
	
	public CharData[] getCharArray() {
		return charArray;
	}
	
	public void destroyFont(){
		GL11.glDeleteLists(charArray[0].listId, 256);
	}
}
